package ferp.center.server.servlet.profile;

import ferp.center.network.request.RequestProfileHacked;
import ferp.center.network.response.ResponseProfileHacked;
import ferp.center.server.Action;
import ferp.center.server.entity.Profile;
import ferp.center.server.entity.Rating;
import ferp.center.server.task.TaskRangeTreeRemoveRating;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * User: olegs
 * Date: 2/19/14 1:32 PM
 */
public class ProfileHacked extends HttpServlet
{
  protected void doPost(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    Action.execute(request, response, RequestProfileHacked.class, new Action.Write<RequestProfileHacked, ResponseProfileHacked>()
    {
      @Override
      public ResponseProfileHacked run(EntityManager em, RequestProfileHacked input) throws IOException
      {
        ResponseProfileHacked result = new ResponseProfileHacked();
        Profile p = input.id == 0 ? null : em.find(Profile.class, input.id);

        result.detached = (p != null);

        if (p != null)
          for (Rating r : p.getRatings())
            TaskRangeTreeRemoveRating.queue(r);

        return result;
      }
    });
  }
}
